package com.slipper.system.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.slipper.common.util.CustomDateFormat;
import com.slipper.system.interceptor.AuthInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${open.url}")
    private String openUrl;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedMethods("*")
                .exposedHeaders(
                        "access-control-allow-headers",
                        "access-control-allow-origin",
                        "access-control-allow-methods",
                        "access-control-max-age",
                        "X-Frame-Options",
                        "Authorization",
                        "Origin",
                        "X-Requested-With",
                        "Content-Type",
                        "Accept",
                        "Access-Token",
                        "Content-Disposition")
                .maxAge(3600);
    }

    /**
     * 排除开放url不进行权限验证
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        List<String> openUrls = Arrays.asList(openUrl.split(","));
        logger.info("arrays openUrl: {}", openUrls);
        registry.addInterceptor(authInterceptor()).excludePathPatterns(openUrls);
    }

    @Bean
    public AuthInterceptor authInterceptor() {
        return new AuthInterceptor();
    }

    /**
     * 使用自定义日期格式化
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> messageConverter : converters) {
            if (messageConverter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) messageConverter).getObjectMapper();
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

                SimpleModule simpleModule = new SimpleModule();
                simpleModule.addDeserializer(String.class, new JsonDeserializer<String>() {
                    @Override
                    public String deserialize(JsonParser p, DeserializationContext dc)
                            throws IOException {
                        if (p == null || p.getText() == null || p.getText().trim().isEmpty()) {
                            return null;
                        } else {
                            return p.getText();
                        }
                    }
                });
                objectMapper.registerModule(simpleModule);

                objectMapper.setDateFormat(new CustomDateFormat());
            }
        }
    }
}
